<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, FormRules } from 'element-plus'
import jyglService from '@/api/jygl'
import zzjgService from '@/api/zzjg'
import dathDialog from '../dialogs/dath-dialog.vue'
import xzdaDialog from '../dialogs/xzda-dialog.vue'
import { useMainStore } from '@/store/main'
import TreeUtilDTO from '@/utils/tree'
import { cloneDeep } from 'lodash'
import dayjs from 'dayjs'
const store = useMainStore()
const emit = defineEmits(['back'])
const props = defineProps({
  item: Object,
})
// 入参
const rightSmall = ref<boolean>(false)
const dragFlag = ref<boolean>(false)
const moveLenHeight = ref<number>(0)

// 初始距离
// 是否按下
const dragstart = () => {
  dragFlag.value = true
}
const dragRight = (e: any) => {
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && window.innerHeight - e.clientY - 26 <= 200) {
    moveLenHeight.value = 200
  } else if (e.clientY && window.innerHeight - e.clientY - 26 >= 500) {
    moveLenHeight.value = 500
  } else {
    moveLenHeight.value = window.innerHeight - e.clientY - 26
  }
}
const dragend = () => {
  dragFlag.value = false
}

const sjdwList = ref()
onMounted(() => {
  zzjgService.getDwbm({ dwbm: store.$state.userInfo?.dwbm }).then((res: any) => {
    sjdwList.value = res.data.data
  })
  getJysqxq(props.item)
})

const getJysqxq = (item: any) => {
  const params = { jysqbh: item.jysqbh }
  jyglService
    .getJysqxq(params)
    .then((res) => {
      form.value = { ...form.value, ...res.data, syfsmc: res.data?.syfsmc.split('+') }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
/*
 * 选择档案
 */
const xzdaRef = ref()
const selectDa = () => {
  xzdaRef.value.openDialog()
}

const ssdaList = ref<any[]>([])
const spdaList = ref<any[]>([])
const addDa = (ssList: any[], spList: any[]) => {
  const cloneSsList = cloneDeep(ssList)
  ssdaList.value.forEach((yda: any) => {
    const da = cloneSsList.find((el) => el.dh === yda.dh)
    const i = cloneSsList.findIndex((el) => el.dh === yda.dh)
    if (da) {
      yda.children = TreeUtilDTO.getTreeData(
        TreeUtilDTO.removeDuplicates(
          [...TreeUtilDTO.flatten(yda.children), ...TreeUtilDTO.flatten(da.children)],
          'dm',
        ).map((el) => ({ ...el, children: null })),
        'dm',
        'fdm',
      )
      cloneSsList.splice(i, 1)
    }
  })
  ssdaList.value = [...ssdaList.value, ...cloneSsList]
  ssdaList.value.forEach((yda: any) => {
    yda.children?.forEach((data: any) => {
      if (data.children && data.children.length > 0) {
        data.sl = 0
        data.children.forEach((data1: any) => {
          data.sl += data1.sl
        })
      }
    })
  })
  spdaList.value = TreeUtilDTO.removeDuplicates([...spdaList.value, ...spList], 'dh')
  nextTick(() => {
    if (ssdaList.value.length) activeDalx.value = 'ssda'
    if (!ssdaList.value.length && spdaList.value.length) activeDalx.value = 'spda'
  })
}
/*
 * 移除档案
 */
// 选择要移除的档案
const multipleSelection = ref<any[]>([])
const check = (val: any[]) => {
  multipleSelection.value = val
}

const ssdaTreeRef = ref<any[]>([])
const getRefs = (el: any, index: number) => {
  ssdaTreeRef.value[index] = el
}

// 选择诉讼档案
const selectSsda = (selection: any[], row: any) => {
  const i = selection.findIndex((da) => da.dh === row.dh)
  const idx = ssdaList.value.findIndex((da) => da.dh === row.dh)
  if (i > -1) {
    nextTick(() => {
      ssdaTreeRef.value[idx]?.setCheckedKeys(selection.map((row) => row.dm))
    })
  } else {
    nextTick(() => {
      ssdaTreeRef.value[idx]?.setCheckedKeys([])
    })
  }
}

// 全选诉讼档案
const selectAllSsda = (selection: any[]) => {
  if (selection.length) {
    nextTick(() => {
      ssdaList.value.forEach((_, i) => {
        ssdaTreeRef.value[i]?.setCheckedKeys(selection.map((row) => row.dm))
      })
    })
  } else {
    nextTick(() => {
      ssdaList.value.forEach((_, i) => {
        ssdaTreeRef.value[i]?.setCheckedKeys([])
      })
    })
  }
}

// 展开诉讼档案
const expandChange = (row: any, expandedRows: any[]) => {
  if (multipleSelection.value.find((da) => da.dh === row.dh)) {
    nextTick(() => {
      const i = ssdaList.value.findIndex((da) => da.dh === row.dh)
      ssdaTreeRef.value[i]?.setCheckedKeys(expandedRows.map((row) => row.dm))
    })
  }
}

// 要移除的档案和目录列表
const checkItems = ref<any[]>([])
// 选择要移除的档案目录
const multipleTableRef = ref()
const checkTree = (checks: any, row: any) => {
  if (checks.checkedNodes.length === TreeUtilDTO.flatten(row.children).length) {
    multipleTableRef.value.toggleRowSelection(row, true)
  } else {
    multipleTableRef.value.toggleRowSelection(row, false)
  }
  const checkRowIndex = checkItems.value.findIndex((item) => item.row.dh === row.dh)
  if (checkRowIndex > -1) {
    checkItems.value.splice(checkRowIndex, 1, {
      row,
      checkNodes: checks.checkedNodes,
    })
  } else {
    checkItems.value.push({
      row,
      checkNodes: checks.checkedNodes,
    })
  }
}
const removeDa = () => {
  if (!checkItems.value.length && !multipleSelection.value.length)
    return ElMessage.warning('请选择移除的目录')
  ElMessageBox.confirm('确定移除选中数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (activeDalx.value === 'ssda') {
      ssdaList.value = ssdaList.value.filter((item: any) => !multipleSelection.value.includes(item))
      checkItems.value.forEach((item) => {
        if (item.checkNodes.length) {
          const tempList = TreeUtilDTO.flatten(cloneDeep(item.row.children))
          const newList = tempList
            .map((el) => ({
              ...el,
              children: null,
            }))
            .filter((el) => !item.checkNodes.find((it: any) => it.dm === el.dm))
          item.row.children = TreeUtilDTO.getTreeData(newList, 'dm', 'fdm')
          if (item.row.children.length === 0) {
            ssdaList.value = ssdaList.value.filter((el: any) => el.dh !== item.row.dh)
          }
        }
      })
      checkItems.value = []
    } else {
      spdaList.value = spdaList.value.filter((item: any) => !multipleSelection.value.includes(item))
    }
    ssdaList.value.forEach((yda: any) => {
      yda.children?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.sl = 0
          data.children.forEach((data1: any) => {
            data.sl += data1.sl
          })
        }
      })
    })
    ElMessage.success('移除成功')
  })
}

/*
 * 提交审批
 */
// 保存调用数据入参
const form = ref<any>({
  jysqbh: '', // 借阅申请数据编号(新增不传)
  jydw: '',
  jydbh: '',
  sqrq: '',
  bmsah: '', // 部门受案号
  jyrdwbm: '', // 借阅单位编码
  jyrdwmc: '', // 借阅单位名称
  sjdwbm: '', // 数据所属单位编码
  sjdwmc: '', // 数据所属单位名称
  jyrbmbm: '', // 借阅人部门编码
  jyrbmmc: '', // 借阅人部门名称
  jyrbh: '', // 借阅人编号
  jyrxm: '', // 借阅人姓名
  jyfsdm: '', // 借阅方式代码
  jyfsmc: '', // 借阅方式名称
  jyts: '', // 借阅天数
  syfsdm: '', // 使用方式代码
  syfsmc: [], // 使用方式名称(打印,下载，查看)
  jymddm: '', // 借阅目的代码
  jymdmc: '', // 借阅目的名称
  jylxdm: '', // 借阅类型代码
  jylxmc: '', // 借阅类型名称
  cxdanr: '', // 查询档案内容
  jymx: '', // 借阅明细
  sfky: 'N', // 是否跨院不能为空
  list: [
    {
      jysjbh: '', // 借阅数据数据编号
      jydalxdm: '', // 借阅档案类型代码
      jydalxmc: '', // 借阅档案类型名称
      jysjlxdm: '', // 借阅数据类型代码
      jysjlxmc: '', // 借阅数据类型名称
      ajbh: '', // 案件信息编号
      dabh: '', // 档案编号
      dwbm: '', // 单位编号
      dwmc: '', // 单位名称
      sjbh: '', // 数据编号
    },
  ], // 借阅数据集
})

// 表单校验
const formRules = reactive<FormRules>({
  sjdwmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  syfsmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  jymdmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  cxdanr: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],
})

const tjsp = () => {
  if (!ssdaList.value.length && !spdaList.value.length) {
    ElMessage.warning('未选择档案，不能提交审批！')
    return
  }
  ElMessageBox.confirm('是否提交审批？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const list: any[] = []
    ssdaList.value.forEach((ssda: any) => {
      list.push({
        ajbh: ssda.ajbh,
        dabh: ssda.dabh,
        dwbm: ssda.ljdwbm,
        dwmc: ssda.ljdw,
        bmbm: ssda.bmbm,
        bmmc: ssda.bmmc,
        jydalxdm: 'gd0420001',
        jydalxmc: '诉讼档案',
        jysjbh: ssda.ajbh,
        jysjlxdm: 'gd0410001',
        jysjlxmc: '案件',
        sjbh: ssda.ajbh,
      })
      TreeUtilDTO.flatten(ssda.children).forEach((item) => {
        list.push({
          ajbh: ssda.ajbh,
          dabh: ssda.dabh,
          dwbm: ssda.ljdwbm,
          dwmc: ssda.ljdw,
          bmbm: ssda.bmbm,
          bmmc: ssda.bmmc,
          jydalxdm: 'gd0420001',
          jydalxmc: '诉讼档案',
          jysjbh: item.cj === '1' ? ssda.ajbh : item.dm,
          jysjlxdm:
            item.cj === '1'
              ? 'gd0410001'
              : item.cj === '2'
              ? 'gd0410003'
              : item.cj === '3'
              ? 'gd0410002'
              : '',
          jysjlxmc:
            item.cj === '1'
              ? '案件'
              : item.cj === '2'
              ? '文书案卷'
              : item.cj === '3'
              ? '文书目录'
              : '',
          sjbh: item.cj === '1' ? ssda.ajbh : item.dm,
        })
      })
    })
    spdaList.value.forEach((spda: any) => {
      list.push({
        ajbh: spda.ajbh,
        dabh: spda.dabh,
        dwbm: spda.dwbm,
        dwmc: spda.ljdw,
        bmbm: spda.bmbm,
        bmmc: spda.bmmc,
        jydalxdm: 'gd0420002',
        jydalxmc: '视频档案',
        jysjlxdm: 'gd0410004',
        jysjlxmc: '视频',
        sjbh: spda.mlbh,
      })
    })
    const params = {
      jysqbh: form.value.jysqbh,
      list,
    }
    jyglService
      .saveDdsj(params)
      .then(() => {
        ElMessage({ type: 'success', message: '提交成功' })
        back()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

/*
 * 调档退回（打开退回弹窗）
 */
const dathRef = ref()
const openTdth = () => {
  dathRef.value.openDialog(form.value)
}

/*
 * 返回
 */
const back = () => {
  emit('back')
}

/**
 * 借阅单关联的档案
 */
// 档案类型
const activeDalx = ref('ssda')

const ssdaTableHeader = [
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    dqfs: 'left',
  },
  { label: '案件名称', prop: 'ajmc', width: 200, dqfs: 'left' },
  { label: '部门受案号', prop: 'bmsah', width: 300, dqfs: 'left' },
  { label: '当事人', prop: 'dsr', width: 120, dqfs: 'left' },
  { label: '案由', prop: 'ay', width: 120, dqfs: 'left' },
  { label: '检察官', prop: 'jcg', width: 120, dqfs: 'left', format: '' },
]

const spdaTableHeader = [
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'ljdw', width: 200, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 120, dqfs: 'left' },
  { label: '题名', prop: 'tm', width: 120, dqfs: 'left' },
  { label: '视频类型', prop: 'splx', width: 120, dqfs: 'left' },
  { label: '录制者', prop: 'lzz', width: 120, dqfs: 'left' },
  {
    label: '录制日期',
    prop: 'lzrq',
    width: 160,
    dqfs: 'left',
    format: 'YYYY-MM-DD',
  },
  { label: '案由', prop: 'aymc', width: null, dqfs: 'left' },
]
</script>
<template>
  <div class="container">
    <div class="action">
      <button class="btn_operation" @click="tjsp">
        <div class="btn-tjsp"></div>
        提交审批
      </button>
      <button class="btn_operation" @click="openTdth">
        <div class="btn-ddth"></div>
        调档退回
      </button>
      <button class="btn_operation" @click="back">
        <div class="btn-tuihui"></div>
        返回
      </button>
    </div>
    <div class="form-box">
      <el-form :model="form" :rules="formRules" ref="filterFormRef" inline label-width="100px">
        <el-row style="width: 100%" :gutter="20">
          <el-col :span="6">
            <el-form-item label="借阅单编号" style="width: 100%">
              <el-input v-model="form.jydbh" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请日期" style="width: 100%">
              <el-date-picker
                style="width: 100%"
                v-model="form.sqrq"
                type="date"
                placeholder="请选择"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅单位" style="width: 100%">
              <el-select
                v-model="form.jyrdwmc"
                clearable
                disabled
                placeholder="请选择"
                style="width: 100%"
              >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借阅人" style="width: 100%">
              <el-input v-model="form.jyrxm" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借阅人部门" prop="mlmc" style="width: 100%">
              <el-select
                v-model="form.jyrbmmc"
                clearable
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅人电话" prop="mlmc" style="width: 100%">
              <el-input v-model="form.jyrdh" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅人邮箱" prop="mlmc" style="width: 100%">
              <el-input v-model="form.jyryx" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅方式" prop="mlmc" style="width: 100%">
              <el-select
                v-model="form.jyfsmc"
                clearable
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅天数" prop="mlmc" style="width: 100%">
              <el-select
                v-model="form.jyts"
                clearable
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
                <el-option label="14" value="14"> </el-option>
                <el-option label="30" value="30"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="档案所属院" prop="sjdwmc" style="width: 100%">
              <el-select
                v-model="form.sjdwmc"
                clearable
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="使用方式" prop="syfsmc" style="width: 100%">
              <el-checkbox-group v-model="form.syfsmc" disabled>
                <el-checkbox label="查看" value="查看"></el-checkbox>
                <el-checkbox label="下载" value="下载"></el-checkbox>
                <el-checkbox label="打印" value="打印"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅类型" prop="sfky" style="width: 100%">
              <el-radio-group v-model="form.sfky" disabled>
                <el-radio value="N">本院</el-radio>
                <el-radio value="Y">跨院</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="借阅目的" prop="jymdmc" style="width: 100%">
              <el-select
                v-model="form.jymdmc"
                clearable
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="查档内容" prop="cxdanr" style="width: 100%">
              <el-input
                disabled
                type="textarea"
                :row="5"
                maxlength="500"
                v-model="form.cxdanr"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!--拖动div-->
    <div
      class="table-drag-box"
      :draggable="true"
      title="可上下拖动"
      @dragstart="dragstart()"
      @dragend="dragend()"
      @drag="dragRight($event)"
    >
      <div class="dragImg">
        <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
      </div>
    </div>

    <div
      class="right-bottom"
      :class="{ small: rightSmall }"
      :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
    >
      <div class="right-img" @click="rightSmall = !rightSmall">
        <img src="@/assets/images/zsq.png" alt="" v-if="!rightSmall" />
        <img src="@/assets/images/ysq.png" alt="" v-else-if="rightSmall" />
      </div>
      <div style="padding-top: 10px">
        <el-button type="primary" @click="selectDa">选择档案</el-button>
        <el-button type="primary" plain @click="removeDa">移除</el-button>
      </div>
      <el-tabs v-if="ssdaList.length || spdaList.length" class="td-tabs" v-model="activeDalx">
        <el-tab-pane
          v-if="ssdaList.length"
          label="&nbsp;&nbsp;&nbsp;&nbsp;诉讼档案&nbsp;&nbsp;&nbsp;&nbsp;"
          name="ssda"
          lazy
        >
        </el-tab-pane>
        <el-tab-pane
          v-if="spdaList.length"
          label="&nbsp;&nbsp;&nbsp;&nbsp;视频档案&nbsp;&nbsp;&nbsp;&nbsp;"
          name="spda"
          lazy
        >
        </el-tab-pane>
      </el-tabs>
      <div class="da-table" v-if="ssdaList.length || spdaList.length">
        <el-table
          ref="multipleTableRef"
          :data="activeDalx === 'ssda' ? ssdaList : spdaList"
          stripe
          height="100%"
          @selection-change="check"
          @expand-change="expandChange"
          @select="selectSsda"
          @select-all="selectAllSsda"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column v-if="activeDalx === 'ssda'" type="expand">
            <template #default="scope">
              <el-tree
                :ref="(el:any) => getRefs(el, scope.$index)"
                style="margin-left: 75px"
                :data="scope.row.children"
                :check-strictly="false"
                :expand-on-click-node="false"
                :props="{ label: 'mc', children: 'children' }"
                node-key="dm"
                highlight-current
                show-checkbox
                @check="(_:any, checks: any)=>checkTree(checks, scope.row)"
              >
                <template #default="{ data }">
                  <span class="custom-tree-node">
                    <span>{{ data.mc }} ({{ data.sl }})</span>
                  </span>
                </template>
              </el-tree>
            </template>
          </el-table-column>
          <el-table-column
            v-for="item in activeDalx === 'ssda' ? ssdaTableHeader : spdaTableHeader"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :min-width="item.width"
            show-overflow-tooltip
            :align="item.dqfs || 'left'"
          >
            <template #default="scope">
              <span v-if="item.format">{{
                scope.row[item.prop] ? dayjs(scope.row[item.prop]).format(item.format) : ''
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <dathDialog ref="dathRef" @refresh="back"></dathDialog>
    <xzdaDialog ref="xzdaRef" @addDa="addDa"></xzdaDialog>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .action {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 12px;
  }
  .form-box {
    flex: 1;
    :deep(.el-form-item) {
      width: 45%;
    }
  }
}

.right-bottom {
  height: 450px;
  // border: 1px solid #dae4f1;
  position: relative;
  overflow-y: auto;
  &.small {
    height: 10px !important;
    border: none !important;
  }
  .right-img {
    z-index: 9;
    cursor: pointer;
    position: absolute;
    left: calc(50% - 4px);
    top: -24px;
    transform: rotate(-90deg);
  }
  .td-tabs {
    height: auto;
    border: 0;
    :deep(.el-tabs__content) {
      height: 0;
      padding: 0;
    }
    :deep(.el-tabs__item) {
      height: 36px;
      padding: 0;
      &:hover,
      &.is-active {
        background-color: transparent;
      }
    }
  }
  .da-table {
    height: calc(100% - 82px);
    padding: 10px 0;
  }
}

.table-drag-box {
  flex-shrink: 0;
  height: 13px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  border-top: 1px solid #dae4f1;
  border-bottom: 1px solid #dae4f1;
  .dragImg {
    height: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
</style>
